//
//  CYNetworkTools.swift
//  CYWeiBo
//
//  Created by Mac on 16/7/16.
//  Copyright © 2016年 Mac. All rights reserved.
//

import UIKit

import AFNetworking

//  定义请求类型的枚举， 第一个默认值0
enum RequestType: Int {
    case GET
    case POST
}


//  网络请求工具类
class CYNetworkTools: AFHTTPSessionManager {
    
    //  网络请求全局访问单例
    static let sharedTools: CYNetworkTools = {
        let tools = CYNetworkTools()
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    
    //  封装get/post请求
    func request(type: RequestType, url: String, params: AnyObject?, callBack: (response: AnyObject?, error: NSError?)->()) {
    
        if type == .GET {
            GET(url, parameters: params, progress: nil, success: { (_, response) -> Void in
                
                callBack(response: response, error: nil)
                }, failure: { (_, error) -> Void in
                    
                    callBack(response: nil, error: error)
            })
        } else {
            POST(url, parameters: params, progress: nil, success: { (_, response) -> Void in
                callBack(response: response, error: nil)
                }, failure: { (_, error) -> Void in
                    callBack(response: nil, error: error)
            })
        }
        
        
    }
    
    
}

//  OAuth登录相关接口
extension CYNetworkTools {
    
    //  通过授权码（code）获取accesstoken
    func requestAccesstoken(code: String, callBack: (response: AnyObject?, error: NSError?) -> ()) {
        
        //  准备接口地址
        let url = "https://api.weibo.com/oauth2/access_token"
        //  准备参数
        let params = [
            "client_id": WeiBoAppkey,
            "client_secret": WeiBoAppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WeiBoRedirect_Url
            
        ]
        
        //  使用通用接口请求
        request(.POST, url: url, params: params, callBack: callBack)


    }
    
    
    // 获取用户信息
    func requestUserInfo(userAccount: CYUserAccount, callBack: (response: AnyObject?, error: NSError?) -> ()) {
        
        //  请求接口地址
        let url = "https://api.weibo.com/2/users/show.json"
        
        //  准备请求参数
        // int64 根字符串放在一起编译不通过，需要转成字符串
        let params = [
            "access_token": userAccount.access_token!,
            "uid": "\(userAccount.uid)",
        ]
        
        request(.GET, url: url, params: params, callBack: callBack)
        
    }
}
